import React, { useRef, useState, useEffect } from 'react';
import { connect } from 'umi';
import TableDataBlock from '@/components/TableDataBlock';
import { reloadTab } from '@/utils/utils';
import { notification } from 'antd';
import { Button, Modal, Space, Form, Row, Col } from 'antd';
import { } from '@/common/contact';
import FormCondition from '@/components/FormCondition';
import { AdminType } from '@/common/contact';
import { useUpdateEffect } from 'ahooks';
const AuthFormSetting = (props) => {
  const {
    visible = false,
    onClose,
    loading,
    organizationAuthAdminList,
    dispatch,
  } = props;
  const { show = false, detail = {}, } = visible;
  const { id, stage } = detail
  const [form] = Form.useForm();
  const [params, setParams] = useState({})
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [stageList, setStageList] = useState([])
  const childRef = useRef();
  useEffect(() => {
    if (show) {
      fetchStage()
      dispatch({
        type: 'weCom/fetchCleanAdmin',
      })
    }
    else {
      setSelectedRowKeys([])
    }
  }, [show])
  const fetchStage = () => {
    dispatch({
      type: 'user/fetchUserStageForChoose',
      payload: {
        queryFor: 'help',
        organizationUserId: id
      },
      callback: (e) => {
        const { stageInfoList = [] } = e
        console.log(stageInfoList)
        setStageList(stageInfoList.map(val => {
          const {
            subStageInfoList = [],
            baseStageFlag,
            mainStage,
            repurchase,
            stageColor,
            stageIdentification,
            stageIndex,
            stageName,
            stageInfo = {}
          } = val
          if (subStageInfoList.length > 0) {
            return {
              ...stageInfo,
              ...val,
              subStageInfoList: subStageInfoList.map(c => {
                return {
                  ...c,
                  mainStage: stageIdentification
                }
              })
            }
          }
          return {
            ...stageInfo,
          }
        }))
        // setStageList(e)
      }
    })
  }
  useUpdateEffect(() => {
    childRef.current.fetchGetData();
  }, [params])
  const rowSelection = {
    type: 'radio',
    hideSelectAll: true,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRows);
    },
    selectedRowKeys: selectedRowKeys.map((item) => {
      return item.id.toString();
    }),
    preserveSelectedRowKeys: true,
  };


  const searchItems = [
    {
      label: '员工姓名',
      name: 'keyword',
    },
  ];
  const formItems = [
    {
      label: `阶段`,
      name: 'stage',
      type: 'stage',
      mode: 'multiple',
      select: stageList,
      onChange: (e, option) => {
        console.log(option)
        setParams({
          stages: option.map(val => {
            return val.stageIdentification
          }).toString(),
          
        })
      },
    },
  ];
  const handleUpAudit = () => {
    if (selectedRowKeys.length === 0) {
      return notification.error({
        title: '温馨提示',
        content: '请选择协助的员工'
      })
    }
    form.validateFields().then((values) => {
      const { stage } = values
      dispatch({
        type: 'subscriber/fakeAddHelpAdmin',
        payload: {
          stageList: stage,
          organizationUserId: id,
          organizationAdminId: selectedRowKeys.map((item) => {
            return item.id;
          }).toString(),

        },
        callback: (e) => {
          onClose()
        }
      })
    });

  };
  const getColumns = [
    {
      title: '姓名',
      dataIndex: 'username',
    },
    {
      title: '岗位类型',
      dataIndex: 'adminType',
      render: (e) => {
        return AdminType[e];
      },
    },
  ];
  const modalProps = {
    title: `协助员工`,
    width: 900,
    visible: typeof visible === 'boolean' ? visible : show,
    maskClosable: true,
    destroyOnClose: true,
    zIndex: 1001,
    confirmLoading: loading,
    footer: <Space>
      <Button onClick={() => onClose()}>取消</Button>
      <Button type='primary' onClick={() => handleUpAudit()}>确定</Button>
    </Space>
  };

  return (
    <Modal {...modalProps} onCancel={onClose} onOk={handleUpAudit}>
      <FormCondition formItemLayouts={{
        labelCol: {

        },
        wrapperCol: {

        },
      }} initialValues={stage} form={form} formItems={formItems}></FormCondition>

      <TableDataBlock
        params={{
          ...params,
        }}
        rowSelection={rowSelection}
        searchItems={searchItems}
        cRef={childRef}
        loading={loading}
        columns={getColumns}
        rowKey={(record) => `${record.id}`}
        firstFetch={false}
        dispatchType="weCom/fetchSearchOrganizationAdmin"
        {...organizationAuthAdminList}
        list={params.stages ? organizationAuthAdminList.list : []}
      ></TableDataBlock>


    </Modal>
  );
};

export default connect(({ weCom, loading }) => ({
  ...weCom,
  loading: loading.models.weCom || loading.models.subscriber,
}))(AuthFormSetting);
